import { Footer } from '@/components';


import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  getFieldPropsOrFormItemProps,
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, history, SelectLang, useIntl, useModel, Helmet } from '@umijs/max';
import { Alert, message, Tabs } from 'antd';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { createStyles } from 'antd-style';
import { Link } from '@umijs/max';
// 全局?默认设置
import Settings from '../../../../config/defaultSettings';

import { loginUsingPost, signupUsingPost } from '@/services/music-recommend/userController';
import { text } from 'express';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    /**
     * @author aunsa
     */
    register: {

    }

  };
});

// 其他登录方式图标
const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
      <Link  to="/user/register" className={styles.register}>
        注册账户
      </Link>
    </>
  );
};


// lang ->language, selectLang-> 选择语言
const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

// 登录操作响应提醒Alert
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  // 用户登录状态
  const [userLoginState, setUserLoginState] = useState<{status?:number}>({status:0});
  // login or signup
  const [type, setType] = useState<string>('login');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const intl = useIntl();

  //signup input state
  const [pwdString,setpwdString] = useState<string>('');
  

  // 用户登录状态
  const { status} = userLoginState;


  const fetchUserInfo = async (userId:number | undefined) => {
    if(!userId) return;

    //TODO: initialState?.fetchUserInfo? 定义在app.tsx
    const userInfo = await initialState?.fetchUserInfo?.();

    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };


  // 处理 login submit
  const handleLogin = async (values: API.UserLoginRequest) => {
    try {
      // 登录
      const  respond= await loginUsingPost({...values});

      if (respond.data && respond.data > 0) {

        message.success('登录成功！');
        localStorage.setItem('userId',respond.data.toString());

        await fetchUserInfo(respond.data);

        const urlParams = new URL(window.location.href).searchParams;

        history.push(urlParams.get('redirect') || '/');
        return;
      }
      console.log(respond.message);
      // 如果失败去设置用户错误信息
      setUserLoginState({status:respond.data});

    } catch (error) {
      console.log(error);
      message.error('登录失败，请重试！');
    }
  };

   // 处理 signup submit
   const handleSignup = async (values: API.UserSignupRequest) => {
    try {
      // 注册

      console.log(values.account +' ' +values.password);

      const  respond = await signupUsingPost({...values});

      if (respond.data && respond.data > 0) {
        message.success('注册成功！');

        const urlParams = new URL(window.location.href).searchParams;

        history.push(urlParams.get('redirect') || '/');
        return;
      }
      console.log(respond.message);
      // 如果失败去设置用户错误信息
      setUserLoginState({status:respond.data});

    } catch (error) {
    

      console.log(error);
      message.error('注册失败，请重试！');
    }
  };




  

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          { '登录页'}
          - {Settings.title}
        </title>
      </Helmet>

      {/* 
      选择语言按钮
      <Lang /> 
      */}
      <br/>

      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="Smart Music"
          subTitle={''}

          //submit按钮的文本设置
          submitter={{ searchConfig: { submitText: (type==='login'?'登录':'注册'),}}}
          
          //初始化变量默认值
          initialValues={{
            autoLogin: true,
          }}

          // actions={[
          //   <FormattedMessage
          //     key="loginWith"
          //     id="pages.login.loginWith"
          //     defaultMessage="其他登录方式"
          //   />,
          //   <ActionIcons key="icons" />,
          // ]}

          // 处理请求
          onFinish={async (values) => {
            if(type=='login'){
              await handleLogin(values as API.UserLoginRequest);
            }
            else if(type == 'signup'){
              await handleSignup(values as API.UserSignupRequest);
            }
            
          }}

        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'login',
                label: '账户密码登录',
              },
              {
                key: 'signup',
                label: '注册',
              },
            ]}
          />

          {/* {status == -1 && type === 'login' && (
            <LoginMessage
              content={'账户或密码错误(root/root)'}
            />
          )} */}

          {type === 'login' && (
            <>
              <ProFormText
                name="account"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名: root'}
                rules={[
                  {
                    required: true,
                    message: "请输入用户名!",
                  },
                ]}
              />

              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码: root'}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                ]}
              />

            </>
          )}

          {/* {status == -1 && type === 'signup' && <LoginMessage content="注册失败" />} */}

          {type === 'signup' && (
            <>
              
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="account"
                placeholder={'手机号'}
                
                rules={[
                  {
                    required: true,
                    message: "请输入手机号！",
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: "手机号格式错误！",
                  },
                ]}
              />

              <ProFormText.Password
                allowClear={true}
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                  onChange: (e)=>{
                    setpwdString(e.target.value.toString());
                  }
                }}
                placeholder={'密码'}
                // 去除前后空格 : 不准输入空格
                getValueFromEvent={(e)=>{
                  return e.target.value.toString().replace(/(^\s*)|(\s*$)/g, '');
                }}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                  {
                    max:50,
                    message:"密码长度过长!"
                  }
                ]}
              />

              <ProFormText.Password
                allowClear={true}
                name="signup_password_confirm"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'确认密码'}
                disabled={pwdString===''}
                // 去除前后空格 : 不准输入空格
                getValueFromEvent={(e)=>{
                  return e.target.value.toString().replace(/(^\s*)|(\s*$)/g, '');
                }}
                rules={[
                  {
                    required: true,
                    message: "请再次输入密码！",
                  },
                  {
                    validator(rule, value, callback) {
                      if(!value) {
                        callback();
                      }
                      let result = pwdString ===value;

                      if (!result) {
                          callback('密码不一致！');
                      }
                      callback();
                    },
                  },
                ]}
              />
            



            </>
          )}

          {/* 自动登录 忘记密码 */}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            {/* <ProFormCheckbox noStyle name="autoLogin">
              "自动登录"
            </ProFormCheckbox> */}
            {/* <a
              style={{
                float: 'right',
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
            </a> */}
          </div>

        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
